<template>
  <qx-table :dbRowClick="rowDblClick" :option="tableOption" :remoteData="remoteData">
    <template v-slot:top>
      <qx-form v-model="searchForm" :option="tableOption" isSearch @submit="startSearch"></qx-form>
    </template>
    <template v-slot:menuLeft>
      <q-btn color="primary" icon="add" unelevated @click="handleCreate">
        {{ $t('Add') }}
      </q-btn>
    </template>
    <template v-slot:menuLeftR>
      <q-icon color="warning" name="mdi-map-marker-question cursor-pointer cursor-hover" size="1.5rem">
        <q-tooltip class="q-pa-md" v-bind="$tooltipAttr">{{ $t('Misc.DblClickCardTips') }}</q-tooltip>
      </q-icon>
    </template>
    <template v-slot:menu="{ row }">
      <q-btn class="col-full-width" color="primary" outline unelevated @click="handleAreaMap(row)">
        {{ $t('MapCore.AreaMapLocationView') }}
      </q-btn>
      <q-btn class="col" color="primary" icon="mdi-square-edit-outline" outline unelevated @click="handleUpdate(row)">
        {{ $t('Edit') }}
      </q-btn>
      <q-btn class="col" color="primary" icon="delete" outline unelevated @click="handleDelete(row)">
        {{ $t('Del') }}
      </q-btn>
      <q-btn v-if="row.isEnable === '0'" class="col" color="primary" outline unelevated
             @click="handleIsEnable(row, '1')">
        {{ $t('Enable') }}
      </q-btn>
      <q-btn v-if="row.isEnable === '1'" class="col" color="primary" outline unelevated
             @click="handleIsEnable(row, '0')">
        {{ $t('Disable') }}
      </q-btn>
    </template>
  </qx-table>
  <q-modal v-model="modalVisible" :header="formInfo.id ? $t('Edit') : $t('Add')" :width="500" btnAlign="center"
           position="right" @beforeClose="beforeClose" @confirm="submitForm">
    <qx-form ref="FormRef" v-model="formInfo" :option="tableOption"></qx-form>
  </q-modal>
  <q-modal v-model="infoVisible" :header="`${$t('Misc.SpecifyDetails')}`" :menuBtn="false" :persistent="false"
           width="620">
    <QInfo :columns="tableOption.column || []" :rowInfo="rowInfo" cols="2" headerWidth="100"></QInfo>
  </q-modal>
  <q-modal v-model="areaMapVisible" v-model:loading="loading" :header="$t('MapCore.AreaMapLocationView')"
           :menuBtn="false" :persistent="false" fullHeight fullWidth>
    <IndexMonitoring :assignedMap="rowInfo" nonHeader nonMaps></IndexMonitoring>
  </q-modal>
</template>
<script setup>
import { i18n } from 'boot/i18n.js'
import { deleteAPI, postAPI, putAPI } from 'src/api/index.js'
import { getRemoteData, setRemoteData } from 'src/enum/ajaxRemoteData.js'
import { enableOrDisable } from 'src/enum/index.js'
import IndexMonitoring from 'src/views/MapCore/IndexMonitoring.vue'
import { computed, onMounted, ref } from 'vue'
import { createDialog, deepClone } from 'src/utils/utils.js'

const rowInfo = ref({})
const formInfo = ref({})
const mapAreas = ref([])
const FormRef = ref(null)
const searchForm = ref({})
const loading = ref(false)
const infoVisible = ref(false)
const modalVisible = ref(false)
const areaMapVisible = ref(false)
const remoteData = ref({ dicUrl: '/tpm/yfagv/api/newMapTrafficAreaRule/list' })
getRemoteData('map_area', '/tpm/yfagv/api/newMapTrafficRule/list').then(data => (mapAreas.value = data))
const congestionTypes = computed(() => {
  return [{
    label: `${i18n.t('Misc.Greater')}`, value: '1'
  }, {
    label: `${i18n.t('Misc.Less')}`, value: '2'
  }]
})
const tableOption = computed(() => {
  return {
    grid: true, span: 22, export: true, labelWidth: 100, searchSpan: 4, headerWidth: 60,
    searchLabelWidth: 60,
    column: [{
      label: `${i18n.t('MapCore.AreaName')}`, field: 'areaCode', type: 'select', options: mapAreas.value,
      minWidth: 100, props: { label: 'mapName, areaName', value: 'areaCode' }, required: true,
      format: (_, row = {}) => `${row.mapName || ''}--${row.areaName || ''}`
    }, {
      label: `${i18n.t('AGVCore.RuleName')}`, field: 'areaRuleName', required: true, minWidth: 100, topLeft: true
    }, {
      label: `${i18n.t('AGVCore.AlarmRule')}`, field: 'areaRuleInfo', required: true, minWidth: 70, search: false,
      display: false, format: (_, { agvSum: count = 0, warnTime: times = 0, congestionType }) => {
        if (congestionType === '1') return `${i18n.t('AGVCore.AlarmRuleTip1', { count, times })}`
        return `${i18n.t('AGVCore.AlarmRuleTip2', { count, times })}`
      }
    }, {
      label: `${i18n.t('Misc.Operator')}`, field: 'congestionType', type: 'radio', search: false, export: false,
      options: congestionTypes.value, value: '1', minWidth: 70, hide: true, showInfo: false
    }, {
      label: `${i18n.t('AGVCore.LimitDeviceCount')}`, field: 'agvSum', type: 'number', min: 0, decimals: 0,
      export: false, minWidth: 70, hide: true, search: false, showInfo: false, required: true
    }, {
      label: `${i18n.t('Misc.Duration')}(s)`, field: 'warnTime', type: 'number', min: 0, decimals: 0, export: false,
      minWidth: 70, hide: true, search: false, showInfo: false, required: true
    }, {
      label: `${i18n.t('IsEnable')}`, field: 'isEnable', type: 'radio', searchType: 'select', value: '1',
      options: enableOrDisable.value, useTag: true, topRight: true, display: false
    }, {
      label: `${i18n.t('Remarks')}`, field: 'remark', type: 'textarea', search: false, minWidth: 120, maxlength: 500,
      hide: true
    }]
  }
})

const handleAreaMap = ({ areaCode }) => {
  loading.value = true
  areaMapVisible.value = true
  postAPI('/tpm/yfagv/api/newMapTrafficAreaRule/mapArea', { areaCode }, data => {
    rowInfo.value = data
    loading.value = false
  }, () => loading.value = false)
}
const handleCreate = () => {
  modalVisible.value = true
}
const rowDblClick = row => {
  rowInfo.value = row
  infoVisible.value = true
}
const handleUpdate = row => {
  formInfo.value = deepClone(row)
  modalVisible.value = true
}
const handleDelete = row => {
  createDialog({ msg: `${i18n.t('DelTips')}` }, () => {
    deleteAPI(`/tpm/yfagv/api/newMapTrafficAreaRule/${row.id}`, {}, () => startSearch('clear'))
  }, () => {})
}
const handleIsEnable = ({ id }, isEnable) => {
  const msg = isEnable === '1' ? `${i18n.t('EnableTips')}` : `${i18n.t('DisableTips')}`
  createDialog({ msg }, () => {
    postAPI('/tpm/yfagv/api/newMapTrafficAreaRule/isEnable', { id, isEnable },
      () => startSearch('clear'))
  }, () => {})
}
const formatSearchForm = () => ({ ...searchForm.value })
const startSearch = (action, done) => {
  remoteData.value.params = formatSearchForm()
  remoteData.value.clearSelected = true
  if (done) done()
  action === 'clear' && setRemoteData('area_alarm_rule')
}
const beforeClose = () => {
  if (FormRef.value) FormRef.value.onReset()
  modalVisible.value = false
}
const submitForm = mDone => {
  FormRef.value.validate((form, done) => {
    const API = form.id ? putAPI : postAPI
    if (!form.isEnable) form.isEnable = '0'
    API('/tpm/yfagv/api/newMapTrafficAreaRule', form, () => {
      startSearch('clear')
      done()
      mDone && mDone()
    }, () => {
      done()
      mDone && mDone(false)
    })
  }, () => mDone && mDone(false))
}
onMounted(startSearch)
</script>